package com.hejjon.syyapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.hejjon.syyapi.bean.ConnectionInfo;
import com.hejjon.syyapi.service.IDbInfoService;
import com.hejjon.syyapi.service.IJDBCService;
import com.hejjon.syyapi.vo.DBConfig;
import com.kern.framework.bean.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * Created by caoshi at 21:58 2021-10-12
 */
@RestController
@RequestMapping("/datasource")
public class DataSourceController {

    private static Logger logger = LoggerFactory.getLogger(DataSourceController.class);

    @Autowired
    private IJDBCService jdbcService;

    @Autowired
    private IDbInfoService dbInfoService;

    @RequestMapping("/testConnection")
    public ResponseResult testConnection(@RequestBody JSONObject params) {
        ConnectionInfo connInfo = new ConnectionInfo();
        connInfo.setUrl(params.getString("url"));
        connInfo.setDriver(params.getString("driver"));
        connInfo.setUsername(params.getString("username"));
        connInfo.setPassword(params.getString("password"));
        return jdbcService.testConnection(connInfo);
    }


    @RequestMapping("/saveDbConfig")
    public ResponseResult saveDbConfig(@RequestBody DBConfig dbConfig) {
        logger.info("保存数据源配置入参: {}", dbConfig);
        String name = dbConfig.getName();
        ResponseResult res = dbInfoService.getByName(name);
        if (res.getData() == null) {
            return dbInfoService.saveOrUpdate(dbConfig);
        } else {
            return new ResponseResult(-1, "数据源名称已存在", "数据源名称已存在", null);
        }

    }






}
